package com.supor.aiot.mine.ui.feedback;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.baseconfig.base.BasePresenter;
import com.android.baseconfig.base.BaseView;
import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.supor.aiot.common.app.api.FileUploadImpl;
import com.supor.aiot.common.app.api.UserImpl;
import com.supor.aiot.common.entity.FeedbackBean;
import com.supor.aiot.common.entity.QuestionTypeBean;
import com.supor.aiot.common.entity.UploadResultBean;
import com.supor.aiot.mine.R;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FeedbackPresenter extends BasePresenter<FeedbackPresenter.FeedbackView> {
    private Dialog successDialog;
    List<QuestionTypeBean> list;

    public FeedbackPresenter(FeedbackPresenter.FeedbackView view, Context context) {
        super(view, context);
        init();
    }

    @Override
    public void init() {
        list = new ArrayList<>();
    }

    @SuppressLint("CheckResult")
    public void getQuestionType() {
        UserImpl.getInstance().getQuestionType().subscribe(dataResult -> {
            if (dataResult.isSuccess()) {
                list = dataResult.data.rows;
                view.questionType(list);
            } else {
                Logc.e("getQuestionType: " + dataResult.status);
            }
        }, throwable -> Logc.e("getQuestionType: " + throwable));
    }

    /**
     * 上传图片
     *
     * @param pathList 图片路径列表
     */
    @SuppressLint("CheckResult")
    public void uploadFeedbackImage(final List<String> pathList) {
        view.showLoading(context.getString(R.string.feedback_loading), false);
        List<File> files = new ArrayList<>();
        for (String s : pathList) {
            File file = new File(s);
            files.add(file);
        }
        FileUploadImpl.getInstance().uploadFiles("file", files).subscribe(result -> {
            Logc.i("uploadFiles: " + result);
            JSONObject jsonObject = new JSONObject(result);
            if ("success".equalsIgnoreCase(jsonObject.getString("result"))) {
                List<UploadResultBean> uploadResultBeans =
                        GsonUtil.getInstance().toObject(jsonObject.getString("fileUrls"),
                                new TypeToken<List<UploadResultBean>>() {
                                }.getType());
                view.uploadFileSuccess(uploadResultBeans);
            } else {
                view.uploadFileFailed(jsonObject.getString("error_message"));
            }
            view.closeLoading();
        }, throwable -> {
            Logc.e("uploadFiles: " + throwable);
            view.uploadFileFailed(throwable.getMessage());
            view.closeLoading();
        });

    }

    /**
     * 反馈接口
     *
     * @param feedbackBean 反馈信息
     */
    @SuppressLint("CheckResult")
    public void feedback(FeedbackBean feedbackBean) {
        view.showLoading(context.getString(R.string.feedback_loading), false);
        UserImpl.getInstance().addFeedback(feedbackBean).subscribe(result -> {
            if (result.isSuccess()) {
                // showSuccessDialog();
                ToastUtils.getInstance().showCustomToast(context.getResources().getString(R.string.submit_success));
                new Handler().postDelayed(this::dismissSuccessDialog, 2000);
            } else {
                view.feedbackFailed(result.status, result.message);
            }
            view.closeLoading();
        }, throwable -> {
            Logc.e("feedback: " + throwable);
            view.feedbackFailed(0, throwable.getMessage());
            view.closeLoading();
        });
    }

    private void showSuccessDialog() {
        if (null != successDialog && successDialog.isShowing()) {
            successDialog.dismiss();
            successDialog = null;
        }
        successDialog = createSuccessDialog(context, context.getResources().getString(R.string.submit_success));
        successDialog.setCancelable(false);
        successDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        successDialog.show();
    }

    private void dismissSuccessDialog() {
        if (null != successDialog && successDialog.isShowing()) {
            successDialog.dismiss();
            successDialog = null;
        }
        ((Activity)context).finish();
    }

    private Dialog createSuccessDialog(Context context, String title) {
        View localView = LayoutInflater.from(context).inflate(R.layout.dialog_create_loading, null);
        LinearLayout localLinearLayout = (LinearLayout) localView.findViewById(R.id.dialog_view);
        localLinearLayout.setBackgroundResource(R.drawable.shape_nodeal_progressdialog);
        localLinearLayout.setPadding(context.getResources().getDimensionPixelSize(R.dimen.dp_38),
                context.getResources().getDimensionPixelSize(R.dimen.dp_25),
                context.getResources().getDimensionPixelSize(R.dimen.dp_38),
                context.getResources().getDimensionPixelSize(R.dimen.dp_30));
        localView.findViewById(R.id.top_progressBar).setVisibility(View.GONE);
        ImageView iv = (ImageView) localView.findViewById(R.id.iv_loading);
        iv.setVisibility(View.VISIBLE);
        ((TextView) localView.findViewById(com.android.baseconfig.R.id.tipTextView)).setText(title);
        iv.setImageResource(R.mipmap.ic_feedback_success);
        Dialog dialog = new Dialog(context, com.android.baseconfig.R.style.loading_dialog);
        dialog.setCancelable(true);
        dialog.setContentView(localLinearLayout, new LinearLayout.LayoutParams(-1, -1));
        return dialog;
    }

    public interface FeedbackView extends BaseView {
        /**
         * 获取问题列表成功
         *
         * @param list
         */
        void questionType(List<QuestionTypeBean> list);

        /**
         * 上传图片成功
         *
         * @param uploadResultBeanList 上传成功后返回URL信息
         */
        void uploadFileSuccess(List<UploadResultBean> uploadResultBeanList);

        /**
         * 上传图片失败
         *
         * @param reason 原因
         */
        void uploadFileFailed(String reason);

        /**
         * 反馈失败
         *
         * @param status 状态码
         * @param reason 原因
         */
        void feedbackFailed(int status, String reason);
    }
}
